package com.onepower.core.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.onepower.core.domain.mapper.MatchInfoMapper;
import com.onepower.core.domain.request.CreateMatchForm;
import com.onepower.core.domain.response.MatchInfo;
import com.onepower.core.modules.repository.entity.*;
import com.onepower.core.modules.repository.mapper.TkdMatchMapper;
import com.onepower.core.modules.service.*;
import com.onepower.core.result.BizResultCode;
import com.onepower.core.result.CommonResult;
import com.onepower.core.utils.ResultUtils;
import com.onepower.core.utils.SecurityUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 比赛表 服务实现类
 * </p>
 *
 * @author kin
 * @since 2018-08-16
 */
@Service
public class TkdMatchServiceImpl extends ServiceImpl<TkdMatchMapper, TkdMatch> implements ITkdMatchService {
    @Autowired
    private IMatchPlaceService matchPlaceService;

    @Autowired
    private IMatchRefereeService matchRefereeService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysUserRoleService userRoleService;

    @Autowired
    private IMatchProjectService matchProjectService;

    @Autowired
    HttpServletRequest request;

    private Map<Integer, String> placeCode = new HashMap<>();

    public TkdMatchServiceImpl() {
        placeCode.put(1, "A");
        placeCode.put(2, "B");
        placeCode.put(3, "C");
        placeCode.put(4, "D");
        placeCode.put(5, "E");
        placeCode.put(6, "F");
        placeCode.put(7, "G");
        placeCode.put(8, "H");
        placeCode.put(9, "I");
        placeCode.put(10, "J");
        placeCode.put(11, "K");
        placeCode.put(12, "L");
        placeCode.put(13, "M");
        placeCode.put(14, "N");
        placeCode.put(15, "O");
        placeCode.put(16, "P");
    }

    @Override
    public CommonResult createMatch(CreateMatchForm form) {
        Integer size = form.getPlaceCount();
        if (size <= 0) {
            return ResultUtils.error(BizResultCode.MATCH_PLACE_NO_NULL);
        }
        TkdMatch match = MatchInfoMapper.MAPPER.converter(form);
        if (form.getMatchDate() != null) {
            match.setMatchTime(form.getMatchDate());
        }
        match.setCreateTime(new Date());
        match.setImportMatch(false);
        baseMapper.insert(match);

        for (int i = 1; i <= size; i++) {
            MatchPlace matchPlace = new MatchPlace();
            matchPlace.setMatchId(match.getId());
            matchPlace.setPlaceName(placeCode.get(i));

            matchPlace.setCreaterId(form.getCreaterId());
            matchPlace.setCreateTime(new Date());
            matchPlaceService.save(matchPlace);

            List<SysUser> matchRefereesUser = new ArrayList<>();

            SysUser user = new SysUser();
            user.setNickName(placeCode.get(i) + "记录台");
            int k = 1000;
            //user.setAccount(placeCode.get(i) + form.getMatchCode().toLowerCase() + Integer.toString(k));
            user.setAccount(placeCode.get(i) + match.getId() + Integer.toString(k));
            Date date = new Date();
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            calendar.add(Calendar.DATE, 30);
            user.setExpiryDate(calendar.getTime());
            user.setPassword(SecurityUtils.generatorPass());
            user.setCreateTime(date);
            user.setCreateUserId(form.getCreaterId());
            user.setMatchId(match.getId());
            int kk = 1001;
            for (int p = 1; p <= form.getRefereeType(); p++) {
                SysUser userRef = new SysUser();

                userRef.setNickName(placeCode.get(i) + Integer.toString(kk));
            //    userRef.setAccount(placeCode.get(i) + form.getMatchCode().toLowerCase() + Integer.toString(kk));
                userRef.setAccount(placeCode.get(i) + match.getId() + Integer.toString(kk));
                kk++;
                calendar.setTime(date);
                calendar.add(Calendar.DATE, 30);
                userRef.setExpiryDate(calendar.getTime());
                userRef.setPassword(SecurityUtils.generatorPass());
                userRef.setCreateTime(date);
                userRef.setCreateUserId(form.getCreaterId());
                userRef.setMatchId(match.getId());
                matchRefereesUser.add(userRef);
            }
            saveAdminReferee(user, matchRefereesUser, match.getId());
        }
        return ResultUtils.ok();
    }

    @Transactional
    @Override
    public void updateMatch(CreateMatchForm form) {
        this.updateById(MatchInfoMapper.MAPPER.converter(form));
        List<MatchProject> updateCollection = form.getMatchProjectList().stream()
                .filter(x -> x.getId() != null)
                .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(updateCollection)) {
            matchProjectService.updateBatchById(updateCollection);
        }

        List<MatchProject> insertCollection = form.getMatchProjectList().stream()
                .filter(x -> x.getId() == null)
                .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(insertCollection)) {
            matchProjectService.saveBatch(insertCollection);
        }
    }

    @Override
    public void deleteMatch(List<Integer> matchIds) {
        List<TkdMatch> matchList = new ArrayList<>();
        matchIds.forEach(x -> {
            TkdMatch tkdMatch = new TkdMatch();
            tkdMatch.setId(x);
            tkdMatch.setDeleteFlag(true);
            matchList.add(tkdMatch);
        });
        if (CollectionUtils.isNotEmpty(matchList)) {
            this.updateBatchById(matchList);
        }
    }

    public String getMatchPullDataUrl(Integer matchId) {
        return baseMapper.selectScoreString(matchId);
    }

    @Override
    public Page<TkdMatch> getList(Integer page, Integer size, Map map) {
        Page<TkdMatch> p = new Page<>(page, size);
        if (SecurityUtils.getCurrentUserId(request) == 8888 || SecurityUtils.getCurrentUserId(request) == 9999){
            p.setRecords(baseMapper.selectMatchList(p, map));

        }else {
            p.setRecords(baseMapper.selectMatchListByMatchId(p, SecurityUtils.getCurrentUserId(request)));
        }
        return p;
    }


    @Override
    public MatchInfo getMatchInfo(Integer matchId) {
        MatchInfo matchInfo = MatchInfoMapper.MAPPER.converterInfo(this.getById(matchId));
        List<MatchProject> matchProjectList = matchProjectService.list(new QueryWrapper<MatchProject>()
                .eq("match_id", matchId));
        matchInfo.setMatchProjectList(matchProjectList);
        return matchInfo;
    }


    private void saveAdminReferee(SysUser matchAdmin, List<SysUser> matchReferees, Integer matchId) {
        matchAdmin.setStatus(0);
        matchAdmin.setCreateTime(new Date());
        List<SysUserRole> userRoleList = new ArrayList<>();
        sysUserService.save(matchAdmin);
        Integer matchAdminId = matchAdmin.getId();

        SysUserRole sysUserRoleMatchAdmin = new SysUserRole();
        sysUserRoleMatchAdmin.setUserId(matchAdminId);
        sysUserRoleMatchAdmin.setRoleId(5);
        userRoleList.add(sysUserRoleMatchAdmin);
        List<Integer> matchRefereeIds = new ArrayList<>();

        matchReferees.forEach(x -> {
            sysUserService.save(x);

            SysUserRole sysUserRoleReferee = new SysUserRole();
            sysUserRoleReferee.setUserId(x.getId());
            sysUserRoleReferee.setRoleId(6);
            userRoleList.add(sysUserRoleReferee);
            matchRefereeIds.add(x.getId());
        });
        userRoleService.saveBatch(userRoleList);
        List<MatchReferee> referees = new ArrayList<>();

        for (int id : matchRefereeIds) {
            MatchReferee referee = new MatchReferee();
            referee.setMatchAdminId(matchAdminId);
            referee.setMatchId(matchId);
            referee.setRefereeId(id);
            referees.add(referee);
        }
        matchRefereeService.saveBatch(referees);
    }
}
